package com.ruoyi.system.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.mapper.CreditUserInfoMapper;
import com.ruoyi.system.domain.CreditUserInfo;
import com.ruoyi.system.service.ICreditUserInfoService;
import com.ruoyi.system.service.ICreditNotificationService;

/**
 * 用户信用信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-28
 */
@Service
public class CreditUserInfoServiceImpl implements ICreditUserInfoService 
{
    private static final Logger logger = LoggerFactory.getLogger(CreditUserInfoServiceImpl.class);
    
    @Autowired
    private CreditUserInfoMapper creditUserInfoMapper;
    
    @Autowired
    private ICreditNotificationService creditNotificationService;

    /**
     * 查询用户信用信息
     * 
     * @param userId 用户信用信息主键
     * @return 用户信用信息
     */
    @Override
    public CreditUserInfo selectCreditUserInfoByUserId(Long userId)
    {
        return creditUserInfoMapper.selectCreditUserInfoByUserId(userId);
    }

    /**
     * 查询用户信用信息列表
     * 
     * @param creditUserInfo 用户信用信息
     * @return 用户信用信息
     */
    @Override
    public List<CreditUserInfo> selectCreditUserInfoList(CreditUserInfo creditUserInfo)
    {
        return creditUserInfoMapper.selectCreditUserInfoList(creditUserInfo);
    }

    /**
     * 新增用户信用信息
     * 
     * @param creditUserInfo 用户信用信息
     * @return 结果
     */
    @Override
    public int insertCreditUserInfo(CreditUserInfo creditUserInfo)
    {
        // 设置默认值
        if (creditUserInfo.getCreditScore() == null) {
            creditUserInfo.setCreditScore(600);
        }
        if (creditUserInfo.getLifeServiceScore() == null) {
            creditUserInfo.setLifeServiceScore(200);
        }
        if (creditUserInfo.getBusinessScore() == null) {
            creditUserInfo.setBusinessScore(200);
        }
        if (creditUserInfo.getSocialScore() == null) {
            creditUserInfo.setSocialScore(200);
        }
        creditUserInfo.setLastUpdateTime(DateUtils.getNowDate());
        creditUserInfo.setCreateTime(DateUtils.getNowDate());
        return creditUserInfoMapper.insertCreditUserInfo(creditUserInfo);
    }

    /**
     * 修改用户信用信息
     * 
     * @param creditUserInfo 用户信用信息
     * @return 结果
     */
    @Override
    public int updateCreditUserInfo(CreditUserInfo creditUserInfo)
    {
        creditUserInfo.setUpdateTime(DateUtils.getNowDate());
        return creditUserInfoMapper.updateCreditUserInfo(creditUserInfo);
    }

    /**
     * 批量删除用户信用信息
     * 
     * @param userIds 需要删除的用户信用信息主键
     * @return 结果
     */
    @Override
    public int deleteCreditUserInfoByUserIds(Long[] userIds)
    {
        return creditUserInfoMapper.deleteCreditUserInfoByUserIds(userIds);
    }

    /**
     * 删除用户信用信息信息
     * 
     * @param userId 用户信用信息主键
     * @return 结果
     */
    @Override
    public int deleteCreditUserInfoByUserId(Long userId)
    {
        return creditUserInfoMapper.deleteCreditUserInfoByUserId(userId);
    }

    /**
     * 根据手机号查询用户信用信息
     * 
     * @param phonenumber 手机号
     * @return 用户信用信息
     */
    @Override
    public CreditUserInfo selectCreditUserInfoByPhonenumber(String phonenumber)
    {
        return creditUserInfoMapper.selectCreditUserInfoByPhonenumber(phonenumber);
    }

    /**
     * 根据身份证号查询用户信用信息
     * 
     * @param idCard 身份证号
     * @return 用户信用信息
     */
    @Override
    public CreditUserInfo selectCreditUserInfoByIdCard(String idCard)
    {
        return creditUserInfoMapper.selectCreditUserInfoByIdCard(idCard);
    }

    /**
     * 检查身份证号唯一性
     * 
     * @param creditUserInfo 用户信用信息
     * @return 结果 true为唯一，false为不唯一
     */
    @Override
    public boolean checkIdCardUnique(CreditUserInfo creditUserInfo)
    {
        Long userId = StringUtils.isNull(creditUserInfo.getUserId()) ? -1L : creditUserInfo.getUserId();
        CreditUserInfo info = creditUserInfoMapper.selectCreditUserInfoByIdCard(creditUserInfo.getIdCard());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return false;
        }
        return true;
    }

    /**
     * 更新用户信用分
     * 
     * @param userId 用户ID
     * @param newScore 新信用分
     * @param reason 变更原因
     * @return 结果
     */
    @Override
    public int updateCreditScore(Long userId, Integer newScore, String reason)
    {
        CreditUserInfo userInfo = creditUserInfoMapper.selectCreditUserInfoByUserId(userId);
        if (userInfo == null) {
            // 如果用户信用信息不存在，创建新记录
            userInfo = new CreditUserInfo();
            userInfo.setUserId(userId);
            userInfo.setCreditScore(newScore);
            userInfo.setLastUpdateTime(new Date());
            userInfo.setCreateTime(new Date());
            
            // 发送通知
            creditNotificationService.sendScoreChangeNotification(userId, 0, newScore, reason);
            
            return creditUserInfoMapper.insertCreditUserInfo(userInfo);
        } else {
            Integer oldScore = userInfo.getCreditScore();
            userInfo.setCreditScore(newScore);
            userInfo.setLastUpdateTime(new Date());
            userInfo.setUpdateTime(new Date());
            
            // 发送通知
            creditNotificationService.sendScoreChangeNotification(userId, oldScore, newScore, reason);
            
            return creditUserInfoMapper.updateCreditUserInfo(userInfo);
        }
    }

    /**
     * 获取用户信用统计信息
     * 
     * @return 统计信息
     */
    @Override
    public Map<String, Object> getCreditStatistics()
    {
        Map<String, Object> stats = new HashMap<>();
        
        // 总用户数
        int totalUsers = creditUserInfoMapper.countTotalUsers();
        stats.put("totalUsers", totalUsers);
        
        // 平均信用分
        Double avgScore = creditUserInfoMapper.getAverageCreditScore();
        stats.put("avgCreditScore", Math.round(avgScore != null ? avgScore : 0));
        
        // 信用分分布
        List<Map<String, Object>> distribution = new ArrayList<>();
        distribution.add(createScoreRange("优秀(800-850)", 800, 850));
        distribution.add(createScoreRange("良好(750-799)", 750, 799));
        distribution.add(createScoreRange("中等(700-749)", 700, 749));
        distribution.add(createScoreRange("一般(650-699)", 650, 699));
        distribution.add(createScoreRange("较差(600-649)", 600, 649));
        stats.put("scoreDistribution", distribution);
        
        return stats;
    }
    
    /**
     * 创建信用分区间统计
     */
    private Map<String, Object> createScoreRange(String name, int minScore, int maxScore)
    {
        Map<String, Object> range = new HashMap<>();
        range.put("name", name);
        range.put("minScore", minScore);
        range.put("maxScore", maxScore);
        // 这里应该从数据库查询实际数量
        range.put("count", 0);
        return range;
    }
    
    /**
     * 获取用户详细信息（包含关联的系统用户信息）
     * 
     * @param userId 用户ID
     * @return 用户详细信息
     */
    @Override
    public Map<String, Object> getUserDetailInfo(Long userId)
    {
        Map<String, Object> result = new HashMap<>();
        
        // 获取信用信息
        CreditUserInfo creditInfo = creditUserInfoMapper.selectCreditUserInfoByUserId(userId);
        result.put("creditInfo", creditInfo);
        
        // 获取基本信息（需要关联sys_user表）
        // 这里可以添加更多关联查询
        
        return result;
    }
    
    /**
     * 批量调整用户信用分
     * 
     * @param adjustments 调整信息列表
     * @return 调整结果
     */
    @Override
    public Map<String, Object> batchAdjustCreditScore(List<Map<String, Object>> adjustments)
    {
        Map<String, Object> result = new HashMap<>();
        int successCount = 0;
        int failCount = 0;
        List<String> errors = new ArrayList<>();
        
        for (Map<String, Object> adjustment : adjustments) {
            try {
                Long userId = Long.parseLong(adjustment.get("userId").toString());
                Integer newScore = Integer.parseInt(adjustment.get("newScore").toString());
                String reason = adjustment.get("reason").toString();
                
                int updateResult = updateCreditScore(userId, newScore, reason);
                if (updateResult > 0) {
                    successCount++;
                } else {
                    failCount++;
                    errors.add("用户ID " + userId + " 调整失败");
                }
            } catch (Exception e) {
                failCount++;
                errors.add("处理调整记录时发生错误: " + e.getMessage());
            }
        }
        
        result.put("successCount", successCount);
        result.put("failCount", failCount);
        result.put("errors", errors);
        
        return result;
    }
    
    /**
     * 获取用户信用分变化历史
     * 
     * @param userId 用户ID
     * @param pageNum 页码
     * @param pageSize 页大小
     * @return 变化历史
     */
    @Override
    public Map<String, Object> getCreditScoreHistory(Long userId, Integer pageNum, Integer pageSize)
    {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 从信用分变化历史表查询数据
            List<Map<String, Object>> historyList = creditUserInfoMapper.selectCreditScoreHistory(userId, pageNum, pageSize);
            int total = creditUserInfoMapper.selectCreditScoreHistoryCount(userId);
            
            result.put("total", total);
            result.put("rows", historyList);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
        } catch (Exception e) {
            logger.error("查询信用分历史记录失败", e);
            // 如果查询失败，返回空数据
            result.put("total", 0);
            result.put("rows", new ArrayList<>());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
        }
        
        return result;
    }

    /**
     * 初始化用户信用信息
     * 
     * @param userId 用户ID
     * @param idCard 身份证号
     * @return 结果
     */
    @Override
    public int initUserCreditInfo(Long userId, String idCard)
    {
        // 检查用户信用信息是否已存在
        CreditUserInfo existingInfo = creditUserInfoMapper.selectCreditUserInfoByUserId(userId);
        if (existingInfo != null) {
            return 1; // 已存在，返回成功
        }
        
        // 创建新的用户信用信息
        CreditUserInfo creditUserInfo = new CreditUserInfo();
        creditUserInfo.setUserId(userId);
        creditUserInfo.setIdCard(idCard);
        creditUserInfo.setCreditScore(600); // 初始信用分
        creditUserInfo.setLifeServiceScore(200); // 生活服务维度分
        creditUserInfo.setBusinessScore(200); // 商业服务维度分
        creditUserInfo.setSocialScore(200); // 亲社会行为维度分
        creditUserInfo.setCreateTime(new Date());
        creditUserInfo.setLastUpdateTime(new Date());
        
        return creditUserInfoMapper.insertCreditUserInfo(creditUserInfo);
    }

    /**
     * 更新用户信用分（带任务信息）
     * 
     * @param userId 用户ID
     * @param scoreChange 分数变化
     * @param taskType 任务类型
     * @param reason 变更原因
     * @param taskId 任务ID（可为null）
     * @return 结果
     */
    @Override
    public boolean updateUserCreditScore(Long userId, Integer scoreChange, String taskType, String reason, Long taskId)
    {
        try {
            CreditUserInfo userInfo = creditUserInfoMapper.selectCreditUserInfoByUserId(userId);
            if (userInfo == null) {
                // 如果用户信用信息不存在，先初始化
                int initResult = initUserCreditInfo(userId, null);
                if (initResult <= 0) {
                    return false;
                }
                userInfo = creditUserInfoMapper.selectCreditUserInfoByUserId(userId);
            }
            
            Integer oldTotalScore = userInfo.getCreditScore();
            Integer newTotalScore = oldTotalScore + scoreChange;
            
            // 根据任务类型更新对应维度分数
            if ("1".equals(taskType)) {
                // 生活服务类任务
                userInfo.setLifeServiceScore(userInfo.getLifeServiceScore() + scoreChange);
            } else if ("2".equals(taskType)) {
                // 商业服务类任务
                userInfo.setBusinessScore(userInfo.getBusinessScore() + scoreChange);
            } else if ("3".equals(taskType)) {
                // 亲社会行为类任务
                userInfo.setSocialScore(userInfo.getSocialScore() + scoreChange);
            }
            
            // 更新总分
            userInfo.setCreditScore(newTotalScore);
            userInfo.setLastUpdateTime(new Date());
            userInfo.setUpdateTime(new Date());
            
            int updateResult = creditUserInfoMapper.updateCreditUserInfo(userInfo);
            
            if (updateResult > 0) {
                // 记录信用分变更历史
                try {
                    // 这里需要注入CreditScoreHistoryMapper，暂时注释掉
                    // CreditScoreHistory history = new CreditScoreHistory();
                    // history.setUserId(userId);
                    // history.setUserName(userInfo.getUserName());
                    // history.setPhonenumber(userInfo.getPhonenumber());
                    // history.setOldScore(oldTotalScore);
                    // history.setNewScore(newTotalScore);
                    // history.setChangeAmount(scoreChange);
                    // history.setReason(reason);
                    // history.setOperator("系统");
                    // history.setChangeType(scoreChange > 0 ? "increase" : (scoreChange < 0 ? "decrease" : "no_change"));
                    // history.setCreateTime(new Date());
                    // creditScoreHistoryMapper.insertCreditScoreHistory(history);
                } catch (Exception e) {
                    // 历史记录失败不影响主流程
                    logger.warn("记录信用分变更历史失败：" + e.getMessage());
                }
                
                // 发送信用分变化通知
                creditNotificationService.sendScoreChangeNotification(userId, oldTotalScore, newTotalScore, reason);
                return true;
            }
            
            return false;
        } catch (Exception e) {
            logger.error("更新用户信用分失败", e);
            return false;
        }
    }
} 